package util

import (
	"encoding/json"
	"log"
	"net/http"
)

type H struct {
	Code int `json:"code"`  //后面加的意思是  转换为json后的字段名
	Msg string `json:"msg"`
	Data interface{} `json:"data,omitempty"`  //omitempty意思是如果值为nil，则不转化此字段
	Rows interface{} `json:"rows,omitempty"`
	Total interface{} `json:"total,omitempty"`
}

func RespFail(w http.ResponseWriter,msg string)  {
	Resp(w,http.StatusBadRequest,nil,msg)
}

func RespOK(w http.ResponseWriter,data interface{},msg string)  {
	Resp(w,http.StatusOK,data,msg)
}

//返回数据
func Resp(w http.ResponseWriter,code int, data interface{},msg string) {
	var h H
	w.Header().Set("Content-Type","application/json")
	w.WriteHeader(http.StatusOK)
	h.Code = code
	h.Data = data
	h.Msg  = msg
	rest,err := json.Marshal(h)
	if err != nil {
		log.Panicln(err.Error())
	}
	_ ,err = w.Write(rest)
	if err != nil {
		log.Panicln(err.Error())
	}
}

func RespOkList(w http.ResponseWriter,lists interface{},total interface{})  {
	//分页数目,
	RespList(w,http.StatusOK,lists,total)
}

func RespList(w http.ResponseWriter,code int, list interface{}, total interface{})  {
	w.Header().Set("Content-Type","application/json")
	h := H{
		Code:code,
		Rows:list,
		Total:total,
	}
	//将结构体转化成JSOn字符串
	ret,err := json.Marshal(h)
	if err!=nil{
		log.Println(err.Error())
	}
	//输出
	w.Write(ret)
}
